<?php
/**
 * Created by Zend Stodio.
 * User: FDG348
 * Date: 2017/12/28
 * Time: 10:36
 */
namespace console\controllers;

use yii\console\Controller;
use linslin\yii2\curl\Curl;
use common\models\LogWeb;

class GetIpAddressController extends Controller{
    /**
     * 执行时间：每天凌晨1点
     * 执行操作：解析IP地址获取城市信息更新到日志表中
     * @param 
     * @return view
     */
    const url = 'http://whois.pconline.com.cn/ip.jsp';
    
    const page = '50';
    
    const sleep = 1;
    
    public function actionGetAddress(){
        $_SERVER['REMOTE_ADDR']='127.0.0.1';
        set_time_limit(0);
        $log_web_count = LogWeb::find()->select('ip')->where('ip_addr is null')->groupBy('ip')->count();
        if ($log_web_count > 0){
            for ($i=1;$i<=ceil($log_web_count / self::page);$i++){
                $limit = ($i-1)*self::page .','.self::page;
                $log_web = LogWeb::find()->select('ip')->where('ip_addr is null')->groupBy('ip')->limit($limit)->asArray()->all();
                if (is_array($log_web) && count($log_web) > 0)foreach ($log_web as $log_web_val){
                    try {
                        error_log('访问日志IP解析处理开始');
                        $ip = $log_web_val['ip'];
                        $address = '';
                        if ($ip){
                            if($ip == '127.0.0.1'){
                                $address = '本机地址';
                            }else{
                                $data = ['ip'=>$ip];
                                $curlModel	= new Curl();
                                $curlModel->setOptions([CURLOPT_SSL_VERIFYPEER=>false]);
                                $curlModel->setGetParams($data);
                                $curlModel->get(self::url);
                                $address = $curlModel->response;
                                if (!$address){
                                    $address = '未知';
                                }else{
                                    $address = str_replace(["\n","\r"], '', iconv("GB2312","UTF-8",$address));
                                }
                            }
                        }else{
                            $address = '未知';
                        }
                        LogWeb::updateAll(['ip_addr'=>$address],'ip=:ip and ip_addr is null',[':ip'=>$ip]);
                        error_log('访问日志IP解析处理结束');
                    } catch (\Exception $e) {
                        error_log($e->getMessage());
                    }
                }
                sleep(self::sleep);
            }
        }
    }
}